<template>
  <div class="container">
       <div class="filter-container">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input class="filter-item" v-model="filterText" placeholder="请输入节点名称" clearable></el-input>
          </el-col>
          <el-col :span="8" class="filter-btn-col">
            <el-button type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
            <el-button type="primary" icon="el-icon-plus" v-permission="{code: 'base:resource:add'}" @click="addMenu">新增一级菜单</el-button>
          </el-col>
        </el-row>
    </div>
    <el-tree
      :data="lists"
      node-key="id"
      :props="defaultProp"
      draggable
      ref="tree"
      @node-drop="handleDrop"
      :allow-drop="allowDrop"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :render-content="renderContent">
    </el-tree>


    <!-- 新增模态窗 -->
    <el-dialog
      :title="(modalEdit?'修改':'新增')+(!addMenuLevel?'一级':'') + '节点'"
      :visible.sync="dialogVisible"
      width="550px"
      center
      @closed="onDialogClose">
      <div class="box">
        <el-form :model="form" ref="form" :rules="rules" label-position="left" label-width="120px">
          <el-form-item label="上级节点名称" v-if="institutionName">
            <span v-text="detailInfo.permissionName || detailInfo.name"></span>
          </el-form-item>
          <el-form-item label="节点名称" prop="permissionName">
            <el-input :maxlength="30" v-model="form.permissionName"></el-input>
          </el-form-item>
           <el-form-item label="节点类型" prop="permissionType" v-if="addMenuLevel">
             <el-select class="filter-item" v-model="form.permissionType" @change="changeValue" placeholder="请选择类型" clearable>
              <el-option label="菜单折叠" :value="0"/>
              <el-option label="页面" :value="1"/>
              <el-option label="按钮" :value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item label="跳转地址" prop="path" v-if="nodeShow">
            <el-input v-model="form.path"></el-input>
          </el-form-item>
           <el-form-item label="组件地址" prop="component" v-if="nodeShow">
            <el-input v-model="form.component"></el-input>
          </el-form-item>
           <el-form-item label="权限标识" prop="permissionCode" v-if="!nodeShow">
            <el-input v-model="form.permissionCode"></el-input>
          </el-form-item>
          <el-form-item label="选择图标" prop="icon" v-if="nodeShow">
            <e-icon-picker v-model="form.icon" :options="options" />
          </el-form-item>
        </el-form>
        
      </div>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button v-db-click type="primary" @click="saveForm">保存</el-button>
      </span>
    </el-dialog>
    
  </div>
</template>

<script>
// import Pagination from "@/components/Pagination";
import getListData from "@/utils/formatTree"
import {
  movePermission,
  addPermission,
  deletePermission,
  updatePermission,
  getPermissionList,
  getPermissionApp,
  getTreeByTenantIdAndGroup
} from '@/api/resource';

export default {
  components: {
    // Pagination,
  },
  name: 'AgencyMange',
  data() {
    return {
      options: {
        FontAwesome: false,
        ElementUI: true,
        eIcon: false,//自带的图标，来自阿里妈妈
        eIconSymbol: false,//是否开启彩色图标
        addIconList: [],
        removeIconList: []
      },
      form: {
        component:'', //组件
        path:'', //路由
        id:'', //主键id
        parentId:'',  //父id 不传则为0 根节点
        permissionCode:'', //权限编码
        permissionGroup:'web',//分组(app,web)
        permissionName:'', //名称
        permissionType:'',//权限类型 不传默认为菜单 1-菜单 2-按钮,示例值(1)
        icon:'' //ico字体图标
      },
      nodeShow:true,//节点类型显示
      filterText: '',
      page: {
        pageSize: 10,
        pageNumber: 1,
        totalElements: 1
      },
      addMenuLevel: 0,
      modalEdit: false,
      dialogTitle: '新增',
      dialogVisible: false,
      institutionName: false,
      addNew: 0,
      rules: {
        permissionName: [{required: true, message: '节点名称是必填的'}],
        permissionType: [{required: true, message: '菜单类型必填的'}],
        component: [{required: true, message: '组件地址必填的'}],
        icon: [{required: true, message: 'icon图标是必填的'}] 
      },
      defaultProp:{
        label: 'permissionName',
        id:'id',
        parentId:'parentId'
    },
      lists: [],
      detailInfo: {},
      activeName: 'first',
      roleName:''
    }
  },
  created () {
    this.getList();
  },
  methods: {
    //tabs选项卡
    handleClick() {
      if(this.activeName == 'first'){
        this.form.permissionGroup = 'web'
        this.getList();
      }else{
        this.getAPPList();
        this.from.permissionGroup = 'app'
      }
      },
      //节点类型
    changeValue(value){
      if(value == 2){
        this.nodeShow = false
      }else{
        this.nodeShow = true
      }
    },
    formatTreeData(){
      this.lists =  getListData(this.lists,0,this.defaultProp)
  },
    // web端获取机构数据
    getList () {
      const data = {
        group: 'web',
        //tenantId:this.sessionData("get","tenantId")
      }
      getTreeByTenantIdAndGroup(data).then(res => {
        this.lists = res.data;
        this.formatTreeData()
      })
    },
     // app端获取机构数据
    getAPPList () {
      getPermissionApp(this.listQuery).then(res => {
        this.lists = res.data;
      })
    },
    // 处理筛选
    handleFilter () {
      // this.page.pageNumber = 1;
      this.$refs.tree.filter(this.filterText);
    },
    // 新增一级菜单
    addMenu () {
        this.addNew = 1
        this.modalEdit = false
        this.nodeShow = true
        this.addMenuLevel = 1;
        this.form.permissionName = ""
        this.form.path = ""
        this.form.id = ""
        this.form.component = ""
        this.form.icon = ""
        this.form.permissionType = ""
        this.form.permissionCode = ""
        this.institutionName = false
        this.dialogVisible = true;
        this.edit = false
    },
    // 显示详情弹窗
    showDialogModal (row, edit) {
        this.nodeShow = true
        this.form.permissionName = ""
        this.form.path = ""
        this.form.id = ""
        this.form.component = ""
        this.form.icon = ""
        this.form.permissionType = ""
        this.form.permissionCode = ""
        this.addNew = 0
        this.modalEdit = edit;
        this.addMenuLevel = 1;
        this.institutionName=true
        this.detailInfo = row;
      if (row.parentId == 0 && edit) this.addMenuLevel = 0;
      if (edit) {
        if(row.permissionType == 2){
          this.nodeShow = false
        }
        this.institutionName = false
        this.form.permissionName = row.permissionName;
        this.form.path = row.path;
        this.form.id = row.id;
        this.form.component = row.component;
        this.form.icon = row.icon;
        this.form.permissionType = row.permissionType;
        this.form.permissionCode = row.permissionCode;
      }
      this.dialogVisible = true;
    },
    // 提交表单
    saveForm () {
      let res = null;
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          let params = {
            ...this.form,
            parentId: this.addMenuLevel && this.detailInfo.id,
          }
          if (this.modalEdit) {
            params.id = this.detailInfo.id;
            params.parentId = this.detailInfo.parentId;
            res = await updatePermission(params);
          }else if(this.addNew == 1){
             params.parentId = 0;
            res = await addPermission(params);
          }else {
            res = await addPermission(params);
          }
          if (res) {
            this.getList();
            this.$message({
              type: 'success',
              message: '保存成功！'
            });
            this.dialogVisible = false;
          }
        } else {
          return false;
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.permissionName.indexOf(value) !== -1;
    },
    // 模态窗关闭事件
    onDialogClose () {
      this.$refs.form.resetFields();
    },
    // 判断是否允许放置
    allowDrop(draggingNode, dropNode, type) {
      // return draggingNode.leave === dropNode.leave;
      return draggingNode.data.parentId === dropNode.data.parentId;
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {
      let params = {
        fid: draggingNode.data.id,
        sid: dropNode.data.id
      }
      movePermission(params).then(res => {
        this.getList();
      });
    },
    renderContent(h, { node, data, store }) {
      return (
        <span class="custom-tree-node">
          <span>{data.permissionName}</span>
            <span>
            { data.permissionType == 1 ?
                <el-button type="text" v-permission={{code: 'base:resource:add'}} size="mini" on-click={() => this.showDialogModal(data, false)}>
                新增子菜单
              </el-button>
              :data.permissionType == 0 ?
                <el-button type="text" v-permission={{code: 'base:resource:add'}} size="mini" on-click={() => this.showDialogModal(data, false)}>
                新增子菜单
              </el-button>
              :null
            }
          {
            data.operable == 1 &&  data.permissionType == 1 ?
              <span><el-button
                type="text"
                size="mini"
                v-permission={{code: 'base:resource:update'}}
                on-click={() => this.showDialogModal({ parentName: node.parent.data.name, ...data}, true)}>
                编辑
              </el-button>
              <el-button
                type="text"
                size="mini"
                v-permission={{code: 'base:resource:delete'}}
                on-click={() => {
                  this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    deletePermission(data.id).then(res => {
                      this.$message({
                        type: 'success',
                        message: '删除成功!'
                      });
                      this.getList();
                    })
                  }).catch(() => {});
                }}>
                删除
              </el-button></span>
            :data.operable == 1 &&  data.permissionType == 2 ?
              <span><el-button
                type="text"
                size="mini"
                v-permission={{code: 'base:resource:update'}}
                on-click={() => this.showDialogModal({ parentName: node.parent.data.name, ...data}, true)}>
                编辑
              </el-button>
              <el-button
                type="text"
                size="mini"
                v-permission={{code: 'base:resource:delete'}}
                on-click={() => {
                  this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    deletePermission(data.id).then(res => {
                      this.$message({
                        type: 'success',
                        message: '删除成功!'
                      });
                      this.getList();
                    })
                  }).catch(() => {});
                }}>
                删除
              </el-button></span>
            :data.operable == 1 &&  data.permissionType == 0 ?
              <span><el-button
                type="text"
                size="mini"
                v-permission={{code: 'base:resource:update'}}
                on-click={() => this.showDialogModal({ parentName: node.parent.data.name, ...data}, true)}>
                编辑
              </el-button>
              <el-button
                type="text"
                size="mini"
                v-permission={{code: 'base:resource:delete'}}
                on-click={() => {
                  this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    deletePermission(data.id).then(res => {
                      this.$message({
                        type: 'success',
                        message: '删除成功!'
                      });
                      this.getList();
                    })
                  }).catch(() => {});
                }}>
                删除
              </el-button></span>
            :null
          }
          </span>
        </span>
      );
    },
  },
  watch: {
   
  },
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}
.box {
  padding: 0 20px;
}
.filter-item {
  width: 100%;
}
.filter-btn-col {
  text-align: end;
}
::v-deep .custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .el-button {
    margin-left: 15px;
  }
}
.el-tabs .el-tabs__content .el-tree{
  
}
</style>